package cn.com.fattiger.framework.cms.core;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Administrator on 2015/12/23.
 */

@Service
@Scope(value = "singleton")
public class Dispatcher {

    ConcurrentHashMap<String, Processor> processors = new ConcurrentHashMap<String, Processor>();
    ConcurrentHashMap<String, Processor> backup = new ConcurrentHashMap<String, Processor>();


    public void register(String service, Processor process) {
        processors.put(service, process);
    }

    public void unregister(String service) {
        processors.remove(service);
    }

    public void pause(String service){
        Processor processor = processors.remove(service);
        backup.put(service, processor);
    }

    public void recovery(String service) {
        Processor processor = backup.remove(service);
        processors.put(service, processor);
    }

    public Object dispatch(RequestObject ro) throws Exception {
        Processor p = processors.get(ro.getService());
        if (null != p) {
            p.validate(ro);
            return p.process(ro);
        } else {
            HashMap<String, Object> response = new HashMap<String, Object>();
            response.put("serialNumber",ro.getSerialNumber());
            response.put("code", 404);
            response.put("message", "no valid service.");
            response.put("timestamp",new Date());
            return response;
        }
    }


}
